package com.lemon.exam.service.impl;

import com.lemon.exam.common.crud.BaseServiceImpl;
import com.lemon.exam.common.exception.CustomException;
import com.lemon.exam.common.util.SecurityUtil;
import com.lemon.exam.entity.po.GradePO;
import com.lemon.exam.repository.GradeRepository;
import com.lemon.exam.service.IGradeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Map;

/**
 * 年级表 服务实现类
 *
 * @author Lemon
 * @since 2025/04/20 22:06:24
 */
@Slf4j
@Service
public class GradeServiceImpl extends BaseServiceImpl<GradePO, Long, GradeRepository> implements IGradeService {
    @Override
    public Mono<String> insert(GradePO param) {
        return Mono.zip(
                super.exist("name", param.getName()),
                SecurityUtil.getUsername()
        ).flatMap(tuple -> {
            if (tuple.getT1()) {
                return Mono.error(new CustomException(402, "年级名称已存在！"));
            } else {
                param.setCreateBy(tuple.getT2());
                return super.insert(param);
            }
        });
    }

    @Override
    public Mono<String> update(GradePO param) {
        return Mono.zip(
                super.exist("name", param.getName(), param.getId()),
                SecurityUtil.getUsername()
        ).flatMap(tuple -> {
            if (tuple.getT1()) {
                return Mono.error(new CustomException(402, "年级名称已存在！"));
            } else {
                param.setUpdateBy(tuple.getT2());
                return super.update(param);
            }
        });
    }

    @Override
    public Flux<GradePO> findGradeIdGradeName() {
        return repository.findGradeIdGradeName();
    }

    @Override
    public Mono<Map<Long, String>> findGradeIdGradeNameByGradeId(List<Long> gradeIdList) {
        return repository.findGradeIdGradeNameByGradeId(gradeIdList).collectMap(GradePO::getId, GradePO::getName);
    }
}
